package com.dg11185.nearshop.activity.shop;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.nearshop.R;
import com.baidu.location.BDLocation;
import com.dg11185.libs.network.NetClient;
import com.dg11185.nearshop.activity.home.SearchActivity;
import com.dg11185.nearshop.activity.shop.ExpandTabHelper.ExpandTabListener;
import com.dg11185.nearshop.app.Constants;
import com.dg11185.nearshop.app.StaticData;
import com.dg11185.nearshop.baidumap.MyMapLocation;
import com.dg11185.nearshop.baidumap.MyMapLocation.MyBDLocationListener;
import com.dg11185.nearshop.baidumap.NearshopActivity;
import com.dg11185.nearshop.baidumap.mai.ShakeListener;
import com.dg11185.nearshop.baidumap.mai.ShakeListener.OnShakeListener;
import com.dg11185.nearshop.net.CacheConstant;
import com.dg11185.nearshop.net.NetCacheClient;
import com.dg11185.nearshop.net.entity.MerchantItem;
import com.dg11185.nearshop.net.request.GetMerchantListRequest;
import com.dg11185.nearshop.net.response.GetMerchantListResponse;
import com.dg11185.nearshop.net.response.NetStatus;
import com.dg11185.nearshop.view.adapter.ShopMainAdapter;
import com.dg11185.nearshop.view.xlistview.XListView;
import com.dg11185.nearshop.view.xlistview.XListView.IXListViewListener;
import com.umeng.analytics.MobclickAgent;
import com.wlper.lib.uitls.ViewUtils;
import com.wlper.lib.view.loading.BaseLoadLayout.LoadStateHandler;
import com.wlper.lib.view.loading.LoadLayoutWithFrameAnim;

/**
 * 商家模块
 * 
 * @author wanliang527
 * @date 2014-5-13
 */
public class ShopFragment extends Fragment implements IXListViewListener, ExpandTabListener, LoadStateHandler {

    public enum ListState {
        INIT, TAB_CHANGE, REFRESH, LOAD_MORE
    };

    private String expandTabTxt[] = new String[] { "全城", "全部分类", "离我最近" };

    /** 加载分页使用的参数 */
    private final static int PAGE_SIZE = 10;

    private int curPageNo = 1;

    private int total = 0;

    /** 百度地图定位相关变量 */
    private MyMapLocation mapLocation = null;

    private BDLocation location = null;

    private ListState listState = ListState.INIT;

    private GetMerchantListRequest request = null;

    private Activity mActivity;

    /** 加载等待 */
    private LoadLayoutWithFrameAnim loadingView = null;

    /** 震动监听器 */
    private ShakeListener shakeListener = null;

    /** listview相关变量 */
    private XListView listView;

    private ShopMainAdapter listAdapter;

    private List<MerchantItem> listDatas;

    private ExpandTabHelper tabHelper = null;

    private Handler handler = new Handler();

    private final static long SHAKE_INTERVAL = 5000;// 摇摇按钮动画启动的时间间隔

    private ImageButton mShakeBtn;// 摇摇按钮

    private Animation shakeAnim;// 晃动动画

    // 新线程，用于控制摇摇按钮的动画效果
    // 每隔5秒，图标晃动一次
    private Runnable mShakeRun = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(mShakeRun, SHAKE_INTERVAL);
            if (mShakeBtn != null && shakeAnim != null) {
                mShakeBtn.startAnimation(shakeAnim);
            }
        }
    };

    /***/
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = getActivity();
        shakeAnim = AnimationUtils.loadAnimation(mActivity, R.anim.shake_anim);
        handler.postDelayed(mShakeRun, SHAKE_INTERVAL);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_shop, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (tabHelper == null) {
            tabHelper = new ExpandTabHelper(mActivity, this);
            tabHelper.initCategoryDBData();
        } else {
            tabHelper.initCategoryView();
            tabHelper.updateTabView(0, expandTabTxt[0]);
            tabHelper.updateTabView(1, expandTabTxt[1]);
            tabHelper.updateTabView(2, expandTabTxt[2]);
        }
        curPageNo = 1;
        listState = ListState.INIT;
        initTopView();
        if (location == null && MyMapLocation.location == null) {
            mapLocation = new MyMapLocation(getActivity(), locationListener);
            mapLocation.start();
        } else {
            if (location == null) {
                location = MyMapLocation.location;
            }
            initListView();
            setLocationValue();
        }

        if (shakeListener == null) {
            shakeListener = new ShakeListener(mActivity);
            shakeListener.setOnShakeListener(new OnShakeListener() {
                @Override
                public void onShake() {
                    startActivity(new Intent(mActivity, NearshopActivity.class));
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        tabHelper.getHelper();
        shakeListener.start();
        MobclickAgent.onPageStart(this.getClass().getName());
    }

    @Override
    public void onPause() {
        shakeListener.stop();
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getName());
    }

    @Override
    public void onDestroyView() {
        NetClient.httpCancel(getActivity(), true);
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        if(tabHelper!=null){
            tabHelper.releseDBHelper();
        }
        super.onDestroy();
    }
    /**
     * 布局文件中所有View的初始化工作都在此进行
     * 
     */
    private void initTopView() {
        LinearLayout middleView = (LinearLayout) getView().findViewById(R.id.llayout_middle);
        TextView titleView = new TextView(mActivity);
        titleView.setTextColor(getResources().getColor(R.color.white));
        titleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, Constants.TITLE_FONT_SIZE);
        titleView.setGravity(Gravity.CENTER);
        titleView.setText("商家");
        middleView.addView(titleView, ViewUtils.WRAP_MATCH);

        /** 查找控件 */
        LinearLayout rightView = (LinearLayout) getView().findViewById(R.id.llayout_right);
        loadingView = (LoadLayoutWithFrameAnim) getView().findViewById(R.id.shop_loading_layout);
        loadingView.setStateHandler(this);
        loadingView.onLoading();
        // 摇摇按钮
        mShakeBtn = new ImageButton(mActivity);
        mShakeBtn.setTag("shake");
        mShakeBtn.setOnClickListener(clickListener);
        mShakeBtn.setBackgroundResource(R.drawable.drawable_tp2tl_gray);
        mShakeBtn.setImageResource(R.drawable.ic_shake_p1);
        rightView.addView(mShakeBtn);
        ((LinearLayout.LayoutParams) mShakeBtn.getLayoutParams()).gravity = Gravity.CENTER;
        // 搜索按钮
        ImageButton searchBtn = new ImageButton(mActivity);
        searchBtn.setTag("search");
        searchBtn.setOnClickListener(clickListener);
        searchBtn.setBackgroundResource(R.drawable.drawable_tp2tl_gray);
        searchBtn.setImageResource(R.drawable.selector_search_btn2);
        rightView.addView(searchBtn);
        ((LinearLayout.LayoutParams) searchBtn.getLayoutParams()).gravity = Gravity.CENTER;
    }

    /** 初始化Listview相关变量 */
    private void initListView() {

        request = new GetMerchantListRequest(Constants.AREA_NUM);
        buildRequest(new int[] { 0, 0 });
        listDatas = new ArrayList<MerchantItem>();
        listAdapter = new ShopMainAdapter(getActivity(), listDatas);
        listView = (XListView) getActivity().findViewById(R.id.shop_main_list);
        listView.setXListViewListener(this);
        listView.setPullLoadEnable(true);
        listView.setAdapter(listAdapter);
        listAdapter.setIndustryMap(tabHelper.getIndustryMap());
        listAdapter.setAreaMap(tabHelper.getAreaMap());

        String areaName = StaticData.AREA_NAME;
        String industryName = StaticData.INDUSTRY_NAME;

        if (!"".equals(industryName)) {

            if (areaName != null && !"".equals(areaName) && !"全城".equals(areaName)) {
                expandTabTxt[0] = areaName;
                tabHelper.updateTabView(0, areaName);
                request.add("areaNum", tabHelper.getAreaMap().get(areaName));
            }
            if (industryName != null && !"".equals(industryName)) {
                if (industryName.equals("美食"))
                    industryName = "餐饮美食";
                else if (industryName.equals("电影"))
                    industryName = "电影院";
                tabHelper.updateTabView(1, industryName);
                if ("其他".equals(industryName)) {
                    request.add("industryId", "106");
                } else {
                    expandTabTxt[1] = industryName;
                    Iterator<Entry<String, String>> iterator = tabHelper.getIndustryMap().entrySet().iterator();
                    while (iterator.hasNext()) {
                        Entry<String, String> entry = iterator.next();
                        if (entry.getKey().contains(industryName)) {
                            request.add("industryId", tabHelper.getIndustryMap().get(entry.getKey()));
                            break;
                        }
                    }
                }
            }
            StaticData.INDUSTRY_NAME = "";
            request.getParams().remove("chshSign");
            request.encryption();
        }
        getListData();
    }

    /**
     * 商家筛选后重新联网获取数据
     * 
     */
    @Override
    public void onTabSelectedChange(int tabBtnPos, String showText, int[] position) {
        if (location == null) {
            return;
        }
        expandTabTxt[tabBtnPos] = showText;
        buildRequest(position);
        listState = ListState.TAB_CHANGE;
        listDatas.clear();
        listView.setPullLoadEnable(true);
        getListData();

    }

    public void buildRequest(int[] position) {
        request.getParams().clear();
        request.add("areaNum", Constants.AREA_NUM);
        if ("全城".equals(expandTabTxt[0])) {

        } else if (ExpandTabHelper.distance[0].equals(expandTabTxt[0])) {
            request.add("latitude", location.getLatitude() + "");
            request.add("longitude", location.getLongitude() + "");
            request.add("radius", "500");
        } else if (ExpandTabHelper.distance[1].equals(expandTabTxt[0])) {
            request.add("latitude", location.getLatitude() + "");
            request.add("longitude", location.getLongitude() + "");
            request.add("radius", "2000");
        } else if (ExpandTabHelper.distance[2].equals(expandTabTxt[0])) {
            request.add("latitude", location.getLatitude() + "");
            request.add("longitude", location.getLongitude() + "");
            request.add("radius", "5000");
        } else if (ExpandTabHelper.distance[3].equals(expandTabTxt[0])) {
            request.add("latitude", location.getLatitude() + "");
            request.add("longitude", location.getLongitude() + "");
            request.add("radius", "10000");
        } else {
            request.add("areaNum", tabHelper.getAreaMap().get(expandTabTxt[0]));
        }

        if ("全部分类".equals(expandTabTxt[1]) || "不限".equals(expandTabTxt[1])) {

        } else if ("其他".equals(expandTabTxt[1])) {
            request.add("industryId", StaticData.getIndustryId(position));
        } else {
            request.add("industryId", tabHelper.getIndustryMap().get(expandTabTxt[1]));
        }
        if (StaticData.getSortFirLevCatalog().get(0).equals(expandTabTxt[2])) {

        } else if (StaticData.getSortFirLevCatalog().get(1).equals(expandTabTxt[2])) {
            request.add("orderName", "avgRating");
            request.add("orderType", "1");
        } else if ("".equals(expandTabTxt[2])) {

        } else if (StaticData.getSortFirLevCatalog().get(2).equals(expandTabTxt[2])) {
            request.add("orderName", "totalComments");
            request.add("orderType", "1");
        } else if (StaticData.getSortFirLevCatalog().get(3).equals(expandTabTxt[2])) {
            if (location != null) {
                request.add("latitude", location.getLatitude() + "");
                request.add("longitude", location.getLongitude() + "");
                request.add("orderName", "radius");
                request.add("radius", Constants.DEFAULT_RADIUS + "");
                request.add("orderType", "0");
            }
        }
        curPageNo = 1;
        request.add("pageNumber", curPageNo + "").add("pageSize", PAGE_SIZE + "").encryption();
    }

    public boolean hideDropWindow() {
        return tabHelper.hideDropWindow();
    }

    /**
     * 按钮监听器
     */
    private View.OnClickListener clickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String tag = v.getTag() == null ? "" : (String) v.getTag();
            if (tag.equals("shake")) {
                shakeListener.onShake();
                startActivity(new Intent(mActivity, NearshopActivity.class));
                return;
            } else if (tag.equals("search")) {
                // **********跳到搜索界面****************//
                Intent intent = new Intent(mActivity, SearchActivity.class);
                startActivity(intent);
                return;
            }

        }
    };

    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                CacheConstant.deleteCacheFolder(Constants.getMerchantList);
                listState = ListState.REFRESH;
                if (mapLocation != null) {
                    mapLocation.reStart();
                }
                curPageNo = 1;
                request.getParams().remove("chshSign");
                request.add("pageNumber", curPageNo + "");
                request.encryption();
                getListData();
            }
        }, 500);
    }

    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                listState = ListState.LOAD_MORE;
                if (curPageNo * PAGE_SIZE >= total) {
                    ViewUtils.showToast(getActivity(), R.string.no_data_anymore);
                    listView.stopLoadMore();
                } else {
                    request.getParams().remove("chshSign");
                    request.add("pageNumber", ++curPageNo + "").encryption();
                    getListData();
                }
            }
        }, 500);
    }

    /** 加载网络数据，刷新界面 */
    private void getListData() {
        if (listState == ListState.INIT || listState == ListState.TAB_CHANGE) {
            loadingView.onLoading();
            listView.setVisibility(View.INVISIBLE);
        }
        request.setActionListener(new GetMerchantListRequest.ActionListener<GetMerchantListResponse>() {
            @Override
            public void onSuccess(GetMerchantListResponse result) {
                if (result.status == NetStatus.SUCCESS) {
                    total = Integer.parseInt(result.total);
                    if (curPageNo * PAGE_SIZE >= total) {
                        listView.setPullLoadEnable(false);
                    } else {
                        listView.setPullLoadEnable(true);
                    }
                    if (total != 0) {
                        loadingView.onLoadSuccess();
                        switch (listState) {
                        case REFRESH:
                            listView.stopRefresh();
                            listDatas.clear();
                            break;
                        case LOAD_MORE:
                            listView.stopLoadMore();
                            break;
                        default:
                            listView.setVisibility(View.VISIBLE);
                            listDatas.clear();
                            break;
                        }
                        listDatas.addAll(result.merchants);
                        listAdapter.notifyDataSetChanged();
                    } else {
                        listView.setVisibility(View.INVISIBLE);
                        loadingView.onNoData();
                    }
                } else {
                    onFailure(-1);
                }
            }

            @Override
            public void onFailure(int resultCode) {
                switch (listState) {
                case REFRESH:
                    listView.stopRefresh();
                    break;
                case LOAD_MORE:
                    listView.stopLoadMore();
                    curPageNo--;
                    break;
                default:
                    break;
                }
                loadingView.onLoadFailed();
                if (resultCode == NetClient.NET_DISCONNECT_CODE) {
                    loadingView.setLoadFailedHint("网络连接错误，连接之后点击重试!");
                } else if (resultCode == -1) {
                    loadingView.setLoadFailedHint("暂时没有符合条件的商家哦! ");
                }
            }

        });

        NetCacheClient.httpCacheGet(mActivity, request);
    }

    private MyBDLocationListener locationListener = new MyBDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation loc) {
            location = loc;
            if (getView() != null) {
                initListView();
                setLocationValue();
            }
        }
    };

    private void setLocationValue() {

        TextView locationTxt1 = (TextView) getActivity().findViewById(R.id.xlistview_header_time1);
        TextView locationTxt = (TextView) getActivity().findViewById(R.id.xlistview_header_time);
        if (locationTxt != null && locationTxt1 != null) {
            locationTxt1.setText("当前位置:");
            if (location.getAddrStr() != null) {
                if (location.getAddrStr().length() > 6) {
                    if ("广东省东莞市".equals(location.getAddrStr().substring(0, 6))) {
                        locationTxt.setText(location.getAddrStr().substring(6));
                    }
                }
            } else {
                locationTxt.setText("广东省 东莞市");
            }
        }
        listView.stopRefresh();
        if (listAdapter != null) {
            listAdapter.setLocation(location);
            listAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onLoading() {

    }

    @Override
    public void onLoadFailed() {

    }

    @Override
    public void onLoadSuccess() {

    }

    @Override
    public void onReload() {
        getListData();
        listState = ListState.INIT;
    }
}
